package com.github.rpc4j.consumer.core;

import java.util.List;

import com.github.rpc4j.common.ServiceRequest;
import com.github.rpc4j.common.ServiceResponse;
import com.github.rpc4j.common.exception.ServiceCallException;
import com.github.rpc4j.common.network.NettyRpcConnection;
import com.github.rpc4j.consumer.clusters.ServiceClustersContext;
import com.github.rpc4j.consumer.zk.ZkUtil;
import com.github.rpc4j.util.IdGenerator;


public class DefaultExecuteHandler implements ConsumerExecuteHandler {
	
	private Rpc4jConsumerContext context;
	
	public DefaultExecuteHandler(Rpc4jConsumerContext context){
		this.context = context;
	}

	@Override
	public Object execute(ServiceRequest request,Object args[]) throws Throwable {
		NettyRpcConnection connection = null;
	    try{
	    	request.setServiceArgs(args);
			ZkUtil zkUtil = context.getZkUtil();
			List<String> serverList = zkUtil.getServiceRegServer(request);
			if(serverList==null||serverList.isEmpty()){
				
			}
			String serviceIp = context.getServiceClustersContext().getCallServer(request.getRequestKey());
			connection = context.getRpcConnectionFactory().getConnection(serviceIp);
			ServiceResponse response = connection.request(request);
			if(response==null){
				System.out.println(connection.getChannel().getId()+ " get cccccccccccccccccccccccc");
			}
			if(response.getThrowable()!=null){
				throw response.getThrowable();
			}else{
			    return response.getResult();	
			}
		}catch(Exception e){
			//throw new ServiceCallException(e);
			return null;
	    }finally{
	    	context.getRpcConnectionFactory().returnConnection(connection);
	    }
	}
}
